<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="库存换标"
    width="1400"
    show-footer
    show-zoom
    resize
    @close="close"
    :z-index="2000"
  >
    <div class="text-[#999999]">
      注：1、若店铺+渠道SKU，存在启用状态的数据，需先禁用该数据；然后才能进行换标操作；
    </div>
    <div class="text-[#999999] ml-[29px]">
      2、无可替换库存：表示未获取到可替换的库存；
    </div>
    <div class="text-[#999999] ml-[29px] mb-4">
      3、换标后系统SKU，支持选择该店铺+渠道SKU已绑定过的系统SKU；同时也支持输入未绑定过的SKU，换标的同时新增绑定；
    </div>

    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="platform" label="平台" width="100" />
      <el-table-column prop="shop_name" label="店铺" width="120" />
      <el-table-column label="换标前" header-align="center">
        <el-table-column prop="state" label="" width="120">
          <template #header>
            <div>渠道SKU</div>
            <div>ASIN</div>
            <div>FNSKU</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.platform_sku }}</div>
            <div>{{ row.asin }}</div>
            <div>{{ row.fn_sku }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="产品中文名称" width="220" />
        <el-table-column prop="sku" label="" width="140">
          <template #header>
            <div>SKU</div>
            <div>自定义SKU</div>
          </template>
          <template #default="{ row }">
            <div>{{ row.goods_sku }}</div>
            <div>{{ row.custom_sku }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="wms_info" label="可替换库存" width="220">
          <template #default="{ row }">
            <template v-if="row.wms_info.length">
              <el-button
                type="primary"
                link
                v-if="checkWMSInfo(row.wms_info)"
                @click="toggleChecked(row)"
                >全选/反选</el-button
              >
              <div v-for="(item, index) in row.wms_info" :key="index">
                <el-checkbox
                  class="w-[200px] whitespace-nowrap break-words"
                  v-model="item.checked"
                  :disabled="Number(item.num) == 0"
                >
                  {{ item.owner_id_text || "--" }} ：<span
                    :class="[Number(item.num) == 0 ? 'text-[#FF0000]' : '']"
                    >{{ Number(item.num) }}</span
                  >
                </el-checkbox>
              </div>
            </template>
            <template v-else><span class="text-[#FF0000]">无可替换库存</span></template>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column
        label="换标后"
        class-name="table-column-class"
        header-align="center"
      >
        <el-table-column
          prop="state"
          label="换标后系统SKU"
          width="130"
          class-name="table-column-class"
        >
          <template #default="{ row }">
            <el-select
              class="w-full"
              v-model="row.new_goods_sku"
              placeholder="请选择换标后SKU"
              :disabled="!row.wms_info || Number(row.wms_info?.num) == 0"
              allow-create
              filterable
              clearable
              @change="blurQuerySKU(row)"
            >
              <el-option
                v-for="(item, index) in row.other_sku"
                :label="item"
                :value="item"
                :key="index"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          prop="replace_product_name"
          label="产品中文名称"
          width="220"
          class-name="table-column-class"
        />
        <el-table-column
          prop="remark"
          label="备注"
          width="160"
          class-name="table-column-class"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder="请输入备注"
              :disabled="!row.wms_info || Number(row.wms_info?.num) == 0"
            ></el-input>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="changeSKU" lang="jsx">
import { reactive, ref, toRefs } from "vue";
import { getReplaceProduct, replaceProduct } from "../api/index.js";
import { querySkuList } from "../../api/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { deepClone } from "@/utils/index.js";

const props = defineProps({
  treeData: {
    type: Array,
    default: () => [],
  },
});
const data = reactive({
  visible: false,
  loading: false,
  tableData: [],
  load: false,
});
const { visible, loading, tableData, load } = toRefs(data);

const open = async (ids) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  getList(ids);
  visible.value = true;
};

const getList = async (ids) => {
  try {
    const res = await getReplaceProduct({ ids });
    res.data.forEach((i) => {
      if (i.wms_info.length) {
        i.wms_info.forEach((j) => {
          if (Number(j.num)) {
            j.checked = true;
          }
        });
      }
    });
    tableData.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const emits = defineEmits(["query"]);

// 文件上传
const save = async () => {
  const messageArray = [];

  const filteredList = tableData.value
    .map((j, k) => {
      // 创建j的深拷贝，以避免修改原对象
      const newObj = deepClone(j);
      newObj.wms_info = newObj.wms_info.filter((i) => i.checked && i.num);

      if (!newObj.new_goods_sku && newObj.wms_info.length) {
        messageArray.push(`第${k + 1}项，换标后SKU不能为空`);
      }
      if (newObj.goods_sku == newObj.new_goods_sku) {
        messageArray.push(`第${k + 1}项，换标前SKU和换标后SKU不允许相同`);
      }

      return newObj.wms_info.length > 0 ? newObj : null;
    })
    .filter(Boolean); // 过滤掉null值，确保filteredList中不包含未通过检查的对象

  console.log(tableData.value);

  if (filteredList.length == 0) {
    return ElMessage.error("暂无替换数据");
  }
  if (messageArray && messageArray.length) {
    ElMessageBox({
      title: "提示",
      message: () => <div>{messageArray.map((d) => h("p", null, d))}</div>,
    });
    return;
  }
  try {
    const res = await replaceProduct({ data: filteredList });
    ElMessage.success("操作成功");
    emits("qury");
    close();
  } catch (e) {
    throw Error(e);
  }
};

function isValidNumber(num) {
  return !isNaN(parseInt(num, 10)) && parseInt(num, 10) > 0;
}

const close = () => {
  visible.value = false;
};
defineExpose({ open });

// 获取sku
const blurQuerySKU = async (row) => {
  if (!row.new_goods_sku) {
    row.replace_product_name = "";
    return;
  }
  try {
    const res = await querySkuList({
      sku: row.new_goods_sku,
    });
    if (res.data.length === 0) {
      ElMessage.error("暂未查询到信息");
    }
    row.replace_product_name = res.data[0].sku_cn_title;
  } catch (e) {
    throw Error(e);
  }
};

// 检测有没有可操作项
const checkWMSInfo = (list) => {
  return list.some((item) => {
    return Number(item.num) > 0;
  });
};

// 全选/反选
const toggleChecked = (row) => {
  const is_checked = row.wms_info.every((item) => {
    return item.checked;
  });
  row.wms_info.forEach((item) => {
    item.checked = !is_checked;
  });
};
</script>
<style lang="scss">
.table-column-class {
  background-color: #e9f3ff !important;
}
</style>
<style lang="scss" scoped></style>
